package com.dooioo.pns.api.leancloud;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dooioo.pns.api.utils.HttpClientUtil;
import com.dooioo.pns.business.service.DeviceInfoService;
import com.dooioo.pns.business.service.DeviceLogoutTaskService;
import com.dooioo.pns.business.service.MessageService;
import com.dooioo.pns.core.config.BaseConfiguration;
import com.dooioo.pns.entity.model.DeviceInfo;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.http.ProtocolException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * PackageName:com.dooioo.pns.api.leancloud
 * Author: Jerry.hu
 * Create: Jerry.hu (2015-07-30 上午8:39)
 * Description:
 * To change this template use File | Settings | File Templates.
 */
@Component
public class LeanCloudRequestUtils {
	@Autowired
	private DeviceInfoService deviceInfoService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private DeviceLogoutTaskService deviceLogoutTaskService;

	private final Logger logger = Logger.getLogger(LeanCloudRequestUtils.class);

	/**
	 * 设备注册 向leanCloud 平台注册，并将lenaCloud 上的注册id 回写到本地的pns 服务器
	 * @param deviceInfo 设备信息
	 * @param headerMap 请求的头部参数
	 */
	@Async
	public void register(DeviceInfo deviceInfo, Map<String,String> headerMap,boolean isLogoutTask){
		logger.info("=====>>>设备注册信息开始==>>");
		Register register = new Register();
		register.setDeviceType(deviceInfo.getPlatform().toString().toLowerCase());
		switch (deviceInfo.getPlatform()){
			case ANDROID:
				register.setInstallationId(deviceInfo.getUuid());
				break;
			case IOS:
				register.setDeviceToken(deviceInfo.getUuid());
				break;
		}
		String[] channels = new String[2];
		channels[0]="a"+deviceInfo.getAppId();
		channels[1]=String.valueOf(deviceInfo.getUserCode());
		register.setChannels(channels);
		int submitCount = 0;
		while (submitCount < 3) {
			try {
				String result = HttpClientUtil.getInstance().doPostJsonResult(BaseConfiguration.getInstance().getLeanCloudUrl(), JSON.toJSONString(register),headerMap);
				JSONObject jsonObject = JSON.parseObject(result);
				String objectId = jsonObject.getString("objectId");
				if(isLogoutTask) {
					deviceLogoutTaskService.update(deviceInfo.getId(),objectId);
				}else{
					deviceInfoService.updateObjectId(deviceInfo.getId(), objectId);

				}
				submitCount= 100;
			} catch (IOException | ProtocolException | ConfigurationException e) {
				submitCount++;
				logger.error("=====>>>设备注册信息失败 执行次数【"+submitCount+"】Register==>>"+register,e);
			}
		}
		logger.info("=====>>>设备注册信息结束==>>");
	}



	/**
	 * 更新leanCloud 上的设备注册信息
	 * @param deviceInfo 设备实体类
	 * @param headerMap 请求头部参数
	 */
	@Async
	public void update(DeviceInfo deviceInfo, Map<String,String> headerMap){
		logger.info("=====>>>更新leanCloud 上的设备注册信息开始 register==>>");
		Register register = new Register();
		register.setDeviceType(deviceInfo.getPlatform().toString().toLowerCase());
		switch (deviceInfo.getPlatform()){
			case ANDROID:
				register.setInstallationId(deviceInfo.getUuid());
				break;
			case IOS:
				register.setDeviceToken(deviceInfo.getUuid());
				break;
		}
		String[] channels = new String[2];
		channels[0]="a"+deviceInfo.getAppId();
		channels[1]=String.valueOf(deviceInfo.getUserCode());
		register.setChannels(channels);
		int submitCount = 0;
		while (submitCount < 3) {
			try {
				HttpClientUtil.getInstance().doPutJsonResult(BaseConfiguration.getInstance().getLeanCloudUrl() + "/" + deviceInfo.getDeviceId(), JSON.toJSONString(register), headerMap);
				submitCount = 100;
			} catch (Exception e) {
				submitCount++;
				logger.error("=====>>>更新leanCloud 上的设备注册信息失败 执行次数【"+submitCount+"】 register==>>" + register, e);
			}
		}
		logger.info("=====>>>更新leanCloud 上的设备注册信息end==>>");
	}

	/**
	 * 发送踢出前一台设备的消息
	 * @param push 消息体
	 * @param headerMap 请求头部参数
	 */
	@Async
	public void logout(DeviceInfo deviceInfo,Push push,Map<String,String> headerMap){
		logger.info("=====>>>发送踢出前一台设备的消开始======");
		push.setProd(getProd());
		int submitCount = 0;
		while (submitCount < 3) {
			try {
				String result = HttpClientUtil.getInstance().doPostJsonResult(BaseConfiguration.getInstance().getLeanPushUrl(), JSON.toJSONString(push), headerMap);
				JSONObject jsonObject = JSON.parseObject(result);
				String objectId = jsonObject.getString("objectId");
				deviceLogoutTaskService.updateInfo(deviceInfo.getId(), 2,objectId);
				submitCount = 100;
			} catch (IOException | ProtocolException | ConfigurationException e) {
				submitCount++;
				logger.error("=====>>>发送踢出前一台设备的消开始失败执行次数【"+submitCount+"】 push==>>" + push, e);
			}
		}
		logger.info("=====>>>发送踢出前一台设备的消结束======");
	}

	/**
	 * 注销设备，本地pns 注销，leanCloud同样注销
	 * @param deviceInfo 设备信息
	 * @param headerMap 请求头部参数
	 */
	@Async
	public void logoff(DeviceInfo deviceInfo, Map<String, String> headerMap,boolean isLogoutTask){
		logger.info("=====>>>注销设备 leanCloud 上的设备注册信息开始==>>");
		int submitCount = 0;
		while (submitCount < 3) {
			try {
				HttpClientUtil.getInstance().doDeleteJsonResult(BaseConfiguration.getInstance().getLeanCloudUrl() + "/" + deviceInfo.getDeviceId(), headerMap);
				if(isLogoutTask) {
					deviceLogoutTaskService.delete(deviceInfo.getId());
				}else {
					deviceInfoService.logout(deviceInfo.getId(), 3);
				}
				submitCount = 100;
			} catch (IOException | ProtocolException | URISyntaxException e) {
				submitCount++;
				logger.error("=====>>>注销设备失败执行次数【"+submitCount+"】 deviceInfo==>>"+deviceInfo,e);
			}
		}
		logger.info("=====>>>注销设备leanCloud 上的设备注册信息结束==>>");
	}

	/**
	 * 消息发送
	 * @param messageId 消息id
	 * @param push 消息发送体
	 * @param headerMap 请求头部参数
	 */
	@Async
	public void send(int messageId,Push push,Map<String,String> headerMap){
		logger.info("=====>>>消息发送开始======");
		push.setProd(getProd());
		int submitCount = 0;
		while (submitCount < 3) {
			try {
				String result =	HttpClientUtil.getInstance().doPostJsonResult(BaseConfiguration.getInstance().getLeanPushUrl(),JSON.toJSONString(push),headerMap);
				JSONObject jsonObject = JSON.parseObject(result);
				String objectId = jsonObject.getString("objectId");
				messageService.updateObjectId(messageId, objectId);
				submitCount = 100;
			} catch (IOException | ProtocolException | ConfigurationException e) {
				submitCount++;
				logger.error("=====>>>消息发送失败执行次数【"+submitCount+"】======>>>【push】"+push,e);
			}
		}
		logger.info("=====>>>消息发送结束======");
	}
	/**
	 * 获取消息发送环境 主要针对ios
	 * @return
	 */
	private String getProd(){
		return BaseConfiguration.getInstance().isProduction() ? "prod" : "dev";
	}

}
